const { app, BrowserWindow, ipcMain, screen } = require('electron');
const path = require('path');
const ping = require('ping');

let mainWindow;

function createWindow() {
  // 获取主屏幕的工作区域
  const primaryDisplay = screen.getPrimaryDisplay();
  const { width, height } = primaryDisplay.workAreaSize;

  // 创建浏览器窗口
  mainWindow = new BrowserWindow({
    width: 380,
    height: 460,
    x: width - 400,  // 默认显示在右上角
    y: 20,
    frame: false,     // 无边框
    transparent: true, // 透明背景
    alwaysOnTop: true, // 始终置顶
    resizable: false,
    skipTaskbar: true, // 不显示在任务栏
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: path.join(__dirname, 'preload.js')
    }
  });

  // 加载 index.html
  mainWindow.loadFile('index.html');

  // 开发模式下打开DevTools
  if (process.argv.includes('--dev')) {
    mainWindow.webContents.openDevTools();
  }

  // 防止窗口被关闭时退出应用
  mainWindow.on('close', (event) => {
    event.preventDefault();
    mainWindow.hide();
  });
}

// 当 Electron 完成初始化时创建窗口
app.whenReady().then(createWindow);

// 当所有窗口被关闭时退出应用（macOS除外）
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  } else {
    mainWindow.show();
  }
});

// IPC 处理器

// Ping目标IP
ipcMain.handle('ping-target', async (event, ip) => {
  try {
    const startTime = process.hrtime.bigint();
    const result = await ping.promise.probe(ip, {
      timeout: 3,
      extra: ['-n', '1'] // Windows ping参数
    });
    const endTime = process.hrtime.bigint();
    
    const latency = result.alive ? 
      parseFloat(result.time) : 
      Number((endTime - startTime) / BigInt(1000000)); // 转换为毫秒

    return {
      success: result.alive,
      latency: latency,
      ip: ip,
      timestamp: Date.now()
    };
  } catch (error) {
    return {
      success: false,
      error: error.message,
      ip: ip,
      timestamp: Date.now()
    };
  }
});

// 获取精确时间
ipcMain.handle('get-precise-time', () => {
  const now = new Date();
  const hrTime = process.hrtime();
  return {
    timestamp: now.getTime(),
    nanoseconds: hrTime[0] * 1000000000 + hrTime[1],
    formatted: now.toISOString()
  };
});

// 窗口控制
ipcMain.on('minimize-window', () => {
  mainWindow.minimize();
});

ipcMain.on('close-window', () => {
  mainWindow.hide();
});

ipcMain.on('toggle-always-on-top', () => {
  const isOnTop = mainWindow.isAlwaysOnTop();
  mainWindow.setAlwaysOnTop(!isOnTop);
});

ipcMain.on('set-opacity', (event, opacity) => {
  mainWindow.setOpacity(opacity);
});

// 处理应用程序关闭
app.on('before-quit', () => {
  mainWindow.removeAllListeners('close');
}); 